from django.db import connection

from app.service import member, order
from libs import time_helper
from libs.db import DB


def app_goods_coupon():
    with connection.cursor() as cursor:
        db = DB('cs_orders', conn=cursor)
        ts = time_helper.date_ts({
            'days': -7
        })
        where = {
            'member_id>0': None,
            'status': -5,
            'coupon_status in (-1, 0)': None,
            'created>=%s': None,
        }
        binds = [ts]
        rows = db.find(['id', 'cashier_id', 'member_id'], where, binds)
        for row in rows:
            cashier_id = row.get('cashier_id')
            cs_order_id = row.get('id')
            member_id = row.get('member_id')
            db_mem = member.get_member_by_id(member_id, cursor, ['username'])
            db_mem_username = db_mem.get('username', '')
            if db_mem.get('username', 0) != '':
                order.update_coupon_status(cashier_id, db_mem_username, cs_order_id)
            else:
                db = DB('cs_orders')
                db.update({'coupon_status': -2}, {'id': cs_order_id})
